package com.tang.client;

import com.google.protobuf.util.JsonFormat;
import com.tang.domain.MsgBody;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

@Slf4j
public class MyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 建立连接
     *
     * @param ctx 连接对象
     * @throws Exception 连接异常
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        SocketChannel socketChannel = (SocketChannel) ctx.channel();
        log.info("链接报告开始！");
        log.info("本客户端链接到服务端了！channelId：{}", socketChannel.id());
        log.info("连接报告IP:{}", socketChannel.localAddress().getHostString());
        log.info("连接报告Port:{}", socketChannel.localAddress().getPort());
        log.info("链接报告完毕！");
        // 通知服务端建立连接成功
        String str = "通知服务端链接建立成功 " + LocalDateTime.now() + " " + socketChannel.localAddress().getHostString() + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * 断开连接
     *
     * @param ctx 连接对象
     * @throws Exception 连接异常
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("断开链接: {}", ctx.channel().localAddress().toString());
    }

    /**
     * 接收消息
     *
     * @param ctx 连接对象
     * @param msg 收到的消息
     * @throws Exception 连接异常
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LocalDateTime now = LocalDateTime.now();
        String message = JsonFormat.printer().print((MsgBody) msg);
        log.info("消息： {}, 获取时间： {}", message, now);
        String str = "客户端在 " + now + " 收到消息: " + message + "\r\n";
        ctx.writeAndFlush(str);
    }

    /**
     * 异常方法
     *
     * @param ctx   连接对象
     * @param cause 错误原因
     * @throws Exception 异常
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        log.info("异常信息：{}\r\n", cause.getMessage());
    }

}
